package com.example.gcm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.gcm.connectserver.JSONParser;
import com.google.android.gcm.GCMRegistrar;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Sender;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class GCMActivity extends Activity {

	private IntentFilter messageReceiverFilter,regIdReceiverFilter,accountsReceiverFilter;
	private TextView tvMessageReceive;
	private EditText etMessageToSend,etToAdrress;
	private Button btnSend;
	private String regId;
	//private int pos;
	private String myRegId= "MyRegId";
	private SharedPreferences prefs;
	public static boolean[] checkBoxState;
	private LayoutInflater inflater;;
	
	
	/*---------------Dialog--------------*/
	private AlertDialog.Builder dialog_register_builder,dialog_accounts_builder;
	private AlertDialog dialog_register,dialog_accounts;
	private EditText etName,etPhone;
	private ListView lvaccounts;
	//private CheckBox cbSelect;
	//private TextView tvPhone,tvName;
	private ProgressBar pBar;
	private ArrayList<HashMap<String, Object>> data;
	/*---------------EndDialog--------------*/
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gcm);
		
		tvMessageReceive = (TextView)findViewById(R.id.tvMessage);
		etToAdrress = (EditText)findViewById(R.id.etToAddress);
		etMessageToSend = (EditText)findViewById(R.id.etMessage);
		btnSend = (Button)findViewById(R.id.btnSend);
		btnSend.setOnClickListener(new View.OnClickListener() 
		{
			
			@Override
			public void onClick(View v) 
			{
				Log.i("message:", etMessageToSend.getText().toString());
				//Log.i("may" + pos,data.get(pos).get("regid"));
				sendMessage(etMessageToSend.getText().toString());
			}
		});	
		
		etToAdrress.setOnClickListener(new View.OnClickListener() 
		{
			
			@Override
			public void onClick(View v) 
			{
				initializeDialogAccount();
				dialog_accounts.show();
				startService(new Intent(GCMActivity.this, getAllAccountsService.class));
			}
		});
		
		inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		messageReceiverFilter = new IntentFilter();
		messageReceiverFilter.addAction("MESSAGE_RECEIVER");
		registerReceiver(messageReceiver, messageReceiverFilter);
		
		regIdReceiverFilter = new IntentFilter();
		regIdReceiverFilter.addAction("REGID_RECEIVER");
		registerReceiver(reIdReceiver, regIdReceiverFilter);
		
		accountsReceiverFilter = new IntentFilter();
		accountsReceiverFilter.addAction("ACCOUNTS_RECEIVER");
		registerReceiver(accountsReceiver, accountsReceiverFilter);
		
		if(getSharedPreferences(myRegId, MODE_PRIVATE).getString("regid", "").equals(""))
			{
				Log.i("First", "no regid");
				GCMRegister();
				initializeDialogRegister();
				dialog_register.show();
			}
	}
	
	private void initializeDialogAccount()
	{
		dialog_accounts_builder = new AlertDialog.Builder(this);
        dialog_accounts_builder.setPositiveButton("OK", new DialogInterface.OnClickListener() 
        {
			
			public void onClick(DialogInterface dialog, int which) 
			{
				dialog_accounts.dismiss();
				etToAdrress.setText("");
				for(int i=0;i<checkBoxState.length;i++)
					if(checkBoxState[i]==true)
						etToAdrress.append((String)data.get(i).get("name")+"; ");						
			}
		});
        
        View view = getLayoutInflater().inflate(R.layout.all_accounts, null);
        
		lvaccounts = (ListView)view.findViewById(R.id.lvAccounts);
		
		/*lvaccounts.setOnItemClickListener(new OnItemClickListener() 
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
			{
				//cbSelect.setSelected(true);
				Log.i("Click", "ok");
				dialog_accounts.dismiss();
				pos = position;
				etToAdrress.append(data.get(position).get("name"));
			}
		});*/
		dialog_accounts_builder.setView(view);
		dialog_accounts = dialog_accounts_builder.create();
	}
	
	private void initializeDialogRegister()
	{
		final TelephonyManager tMgr =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);				
		dialog_register_builder = new AlertDialog.Builder(this);
        dialog_register_builder.setPositiveButton("OK", new DialogInterface.OnClickListener() 
        {
			
			public void onClick(DialogInterface dialog, int which) 
			{
				String [] data = new String[]{
						etName.getText().toString(),
						tMgr.getLine1Number(),
						getSharedPreferences(myRegId, MODE_PRIVATE).getString("regid", ""),
						
				};
				new registerService().execute(data);
				pBar.setVisibility(0);				
			}
		});
        
        View view = getLayoutInflater().inflate(R.layout.add_account, null);
        
		etName = (EditText)view.findViewById(R.id.etName);
		etPhone = (EditText)view.findViewById(R.id.etPhone);
		etPhone.setText(tMgr.getLine1Number());
		etPhone.setEnabled(false);
		
		pBar = (ProgressBar)view.findViewById(R.id.progressBar);
		pBar.setVisibility(8);
		
		dialog_register_builder.setView(view);
		dialog_register = dialog_register_builder.create();
	}
	
	private class registerService extends AsyncTask<String, Integer, String>
	{	
		@Override
		protected String doInBackground(String... data) 
		{
			JSONParser jsonParser = new JSONParser();
			
			// url to create new product
			String url_create_product = "http://10.0.2.2/gcm_server/create_account.php";

			// JSON Node names
			String TAG_SUCCESS = "success";
			Log.i("regidupload", data[2]);
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("name", data[0]));
			params.add(new BasicNameValuePair("phone", data[1]));
			params.add(new BasicNameValuePair("regid", data[2]));
						
			// getting JSON Object
			// Note that create product url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(url_create_product,"POST", params);
						
			// check log cat fro response
			Log.d("Create Response", json.toString());

			// check for success tag
			try 
			{
					int success = json.getInt(TAG_SUCCESS);

					if (success == 1) 
						Log.i("regiter", "Congratulations! You have successfully registered");
					
					else 
						Log.i("regiter", "failed to register");					
			
			} 
			
			catch (JSONException e) 
			{
					e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) 
		{
			super.onPostExecute(result);
			pBar.setVisibility(8);
			dialog_register.dismiss();
		}

		
	}
	
	@Override
	protected void onDestroy() 
	{
		super.onDestroy();
		unregisterReceiver(messageReceiver);
		unregisterReceiver(reIdReceiver);
		unregisterReceiver(accountsReceiver);
	}



	private void sendMessage(String msg)
	{
		try {

			Sender sender = new Sender("AIzaSyAQ7LQ37qpKFGsWrGvIWHSeVeMolHvMSFA");

			ArrayList<String> devicesList = new ArrayList<String>();
			for(int i=0;i<checkBoxState.length;i++)
				if(checkBoxState[i]==true)
					devicesList.add((String)data.get(i).get("regid"));
			//devicesList.add("APA91bGGmBwumCX_BXz2Am5u2mSQrFgazc8aq5HIbAkx9IV0PswO3jPsshfAgSR3qws3VQdHw4FHf60ks0ntFM4h3oaIC5edp8m11lCI8ko1tWf3TGcfwjkX2wmOaSjhWy9YxbsFZydmnEiJboQDfvRhXX-Y0GA2gw");

			// Use this line to send message without payload data
			// Message message = new Message.Builder().build();

			// use this line to send message with payload data
			Message message = new Message.Builder()
													.collapseKey("You have a message!")
													.timeToLive(3)
													.delayWhileIdle(true)
													.addData("message",msg)
													.build();

			// Use this code to send to a single device
			// Result result = sender
			// .send(message,
			// "APA91bGiRaramjyohc2lKjAgFGpzBwtEmI8tJC30O89C2b3IjP1CuMeU1h9LMjKhmWuZwcXZjy1eqC4cE0tWBNt61Kx_SuMF6awzIt8WNq_4AfwflaVPHQ0wYHG_UX3snjp_U-5kJkmysdRlN6T8xChB1n3DtIq98w",
			// 1);

			// Use this for multicast messages
			MulticastResult result = sender.send(message, devicesList, 1);
			sender.send(message, devicesList, 1);

			System.out.println(result.toString());
			if (result.getResults() != null) 
			{
				int canonicalRegId = result.getCanonicalIds();
				if (canonicalRegId != 0) 
				{
				}
			} 
			
			else 
			{
				int error = result.getFailure();
				System.out.println(error);
			}
		} 
		
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	private void GCMRegister()
	{
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		
		if (GCMRegistrar.isRegistered(this)) 
			Log.d("info", GCMRegistrar.getRegistrationId(this));
		
		regId = GCMRegistrar.getRegistrationId(this);
		Log.d("regId la: ", regId);
		if (regId.equals("")) 
		{
			// replace this with the project ID
			GCMRegistrar.register(this, "516639321860");
			Log.d("info", GCMRegistrar.getRegistrationId(this));
			
		} 
			
		else 
			Log.d("info", "already registered as" + regId);
		
				
	}
	
	private BroadcastReceiver messageReceiver = new BroadcastReceiver()
	{

		@Override
		public void onReceive(Context context, Intent intent) 
		{
			Log.i("mess", intent.getStringExtra("mess"));
			tvMessageReceive.append(Html.fromHtml(intent.getStringExtra("mess")+"<br/>"));
		}
		
	};
	
	private BroadcastReceiver reIdReceiver = new BroadcastReceiver()
	{

		@Override
		public void onReceive(Context context, Intent intent) 
		{
			prefs = getSharedPreferences(myRegId, MODE_PRIVATE);
			SharedPreferences.Editor editor = prefs.edit();
			
			editor.putString("regid", intent.getStringExtra("regId"));
			editor.commit();
		}
		
	};
	
	private BroadcastReceiver accountsReceiver = new BroadcastReceiver()
	{

		@SuppressWarnings("unchecked")
		@Override
		public void onReceive(Context context, Intent intent) 
		{
			Bundle extras = intent.getExtras();
			
			if(extras!=null)
			{
				data = (ArrayList<HashMap<String, Object>>) extras.getSerializable("datasend");
				if(data!=null && data.size()>0)
				{
					//SimpleAdapter simpleAdapter = new SimpleAdapter(GCMActivity.this, data, R.layout.row, new String[]{"name","phone"}, new int[]{R.id.tvName,R.id.tvPhone});
					
					CustomAdapter adapter = new CustomAdapter(GCMActivity.this, inflater, R.layout.row, data);
					lvaccounts.setAdapter(adapter);
				}
			}
			
		}
		
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_gcm, menu);
		return true;
	}

}
